#include "common.h"
#include "slider.h"

void init_slider(slider* s, char* text, int x, int y, int w, int h, float frac)
{
	s->groove_rect.x = x;
	s->groove_rect.y = y;
	s->groove_rect.h = h;
	s->groove_rect.w = w;

	s->handle_rect.h = 20;
	s->handle_rect.w = 60;
	s->handle_rect.x = (x+(w/2))-30;
	s->handle_rect.y = y;

	s->rect.x = (x+(w/2))-30;
	s->rect.y = y; 
	s->rect.h = h; 
	s->rect.w = 60;

	set_slider_fraction(s, frac);

	// setup text surface
	TTF_Font* font = TTF_OpenFont("/usr/share/fonts/arial.ttf", 16);
	SDL_Color color = {0xFF,0xFF,0xFF};
	s->text = TTF_RenderText_Solid(font, text, color);
	TTF_CloseFont(font);
}

int touch_slider(slider* s, int x, int y)
{
	if (!INSIDE_RECT(s->rect, x, y))
		return 0;

	s->handle_rect.y = y-((s->handle_rect.h)/2.0);
	return 1;
}

void free_slider(slider* s)
{
	SDL_FreeSurface(s->text); 
}

void display_slider(SDL_Surface* screen, slider* s)
{
	SDL_Rect text_offset;
	text_offset.x = s->handle_rect.x + (0.5*(s->handle_rect.w-s->text->w));
	text_offset.y = s->handle_rect.y;

	SDL_FillRect(screen, &s->groove_rect, SDL_MapRGB(screen->format, 0xAA, 0xAA, 0xAA));
	SDL_FillRect(screen, &s->handle_rect, SDL_MapRGB(screen->format, 0xFF, 0x00, 0x00));
	SDL_BlitSurface(s->text, NULL, screen, &text_offset);
}

float get_slider_fraction(slider* s)
{
	return 1.0-((float)(s->handle_rect.y-s->groove_rect.y)/(float)s->groove_rect.h);
}

float set_slider_fraction(slider* s, float frac)
{
	s->handle_rect.y = s->groove_rect.y+((float)s->groove_rect.h*(1.0-frac));
}
